package com.jhd.fuzhou.view.daily;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.DocumentService;
import com.jhd.fuzhou.util.BusinessStatus;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.vo.AdministrativeAccessoryVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.SupervisedUnitVo;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class DocumentDetailActivity extends BaseActivity {
    private String type,id;//监督类型，1-日常监督  2-双随机 3-专项监督 4-量化评级
    @BindView(R.id.tv_unitName)TextView tv_unitName;
    @BindView(R.id.tv_manage_status)TextView tv_manage_status;
    @BindView(R.id.tv_creditCode)TextView tv_creditCode;
    @BindView(R.id.tv_superviseSector)TextView tv_superviseSector;//监管机构
    @BindView(R.id.tv_superviseOffice)TextView tv_superviseOffice;//监管部门
    @BindView(R.id.tv_date)TextView tv_date;
    @BindView(R.id.tv_inspectResult)TextView tv_inspectResult;
    @BindView(R.id.tv_specialityCategory)TextView tv_specialityCategory;
    @BindView(R.id.tv_specialityDetail)TextView tv_specialityDetail;
    @BindView(R.id.tv_firstSupervisorName)TextView tv_firstSupervisorName;
    @BindView(R.id.tv_secondSupervisorName)TextView tv_secondSupervisorName;
    @BindView(R.id.tv_accompanyName)TextView tv_accompanyName;
    @BindView(R.id.tv_task_type)TextView tv_task_type;
    @BindView(R.id.tv_order_no)TextView tv_order_no;
    @BindView(R.id.tv_grade)TextView tv_grade;
    @BindView(R.id.tv_title)TextView tv_title;
    @BindView(R.id.rel_task_type)RelativeLayout rel_task_type;
    @BindView(R.id.rel_order_no)RelativeLayout rel_order_no;
    @BindView(R.id.rel_grade)RelativeLayout rel_grade;
    @BindView(R.id.rv_document)RecyclerView rv_document;
    private Call<JsonForResult> jsonForResultCall;
    private Context context=this;
    private SupervisionInspectionVo supervisionInspectionVo;
    private LinearLayoutManager layoutManager;
    private List<SuperviseEnclosureVo> superviseEnclosureVoList;
    private List<SuperviseEnclosureVo> superviseEnclosureVos=new ArrayList<>();//根据后缀pdf筛选可以打印的文件
    public ProgressDialog _dialog;
    private SupervisedUnitVo supervisedUnitVo;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_document_detail);
    }

    @Override
    protected void processLogic() {
        onBack();
        if("4".equals(type))tv_title.setText("评级详情");
        layoutManager = new LinearLayoutManager(context);
        rv_document.setLayoutManager(layoutManager);
        type=getIntent().getStringExtra("type");
        id=getIntent().getStringExtra("id");
        supervisedUnitVo= JSON.parseObject(getIntent().getStringExtra("supervisionUnit"),SupervisedUnitVo.class);
        getSuperviseInspectionVo();
        if(!"4".equals(type)){
            _dialog=new ProgressDialog(context);
            _dialog.setMessage("正在获取监督详情,请稍等...");
            _dialog.show();
        }
    }
    private void setDate(SupervisionInspectionVo supervisionInspectionVo){
        tv_unitName.setText(StringUtil.isNullOrEmpty(supervisedUnitVo.getUnitName())?"":supervisedUnitVo.getUnitName());
        if(!"1".equals(supervisedUnitVo.getBusinessStatus())){
            tv_manage_status.setTextColor(getResources().getColor(R.color.red));
        }
        tv_manage_status.setText(supervisedUnitVo.getBusinessStatus().equals("1")?"正常":"关闭");
        tv_creditCode.setText(StringUtil.isNullOrEmpty(supervisedUnitVo.getCreditCode())?"":supervisedUnitVo.getCreditCode());
        tv_superviseSector.setText(StringUtil.isNullOrEmpty(supervisedUnitVo.getSuperviseSector())?"":supervisedUnitVo.getSuperviseSector());
        tv_superviseOffice.setText(StringUtil.isNullOrEmpty(supervisedUnitVo.getSuperviseOffice())?"":supervisedUnitVo.getSuperviseOffice());
        tv_date.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getReportDate())?"":supervisionInspectionVo.getReportDate().substring(0,10));

        if("0".equals(supervisionInspectionVo.getInspectResult())){
            tv_inspectResult.setTextColor(getResources().getColor(R.color.red));
        }
        tv_inspectResult.setText("1".equals(supervisionInspectionVo.getInspectResult())?"合格":"不合格");
        tv_specialityCategory.setText(StringUtil.isNullOrEmpty(supervisedUnitVo.getSpecialityCategory())?"":supervisedUnitVo.getSpecialityCategory());
        tv_specialityDetail.setText(StringUtil.isNullOrEmpty(supervisedUnitVo.getSpecialityDetail())?"":supervisedUnitVo.getSpecialityDetail());
        tv_firstSupervisorName.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getFirstSupervisorName())?"":supervisionInspectionVo.getFirstSupervisorName());
        tv_secondSupervisorName.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getSecondSupervisorName())?"":supervisionInspectionVo.getSecondSupervisorName());
        tv_accompanyName.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getAccompanyName())?"":supervisionInspectionVo.getAccompanyName());
        if("4".equals(type)){
            rel_grade.setVisibility(View.VISIBLE);
            tv_grade.setText(supervisionInspectionVo.getGrade());
        }
        if("2".equals(type)){
            rel_task_type.setVisibility(View.VISIBLE);rel_order_no.setVisibility(View.VISIBLE);
            tv_task_type.setText("0".equals(supervisionInspectionVo.getTaskType())?"国家双随机":"省双随机");
            tv_order_no.setText(supervisionInspectionVo.getDoubleRandomTaskNumber()==null?"":supervisionInspectionVo.getDoubleRandomTaskNumber());
        }
        if("1".equals(type)){
            superviseEnclosureVoList=supervisionInspectionVo.getSuperviseEnclosureVoList();
        }else if("2".equals(type)||"3".equals(type)){
            superviseEnclosureVoList=supervisionInspectionVo.getDocumentAttachmentList();
        }else if("4".equals(type)){
            superviseEnclosureVoList=JSON.parseArray(getIntent().getStringExtra("gradeReportEnclosureVoList"),SuperviseEnclosureVo.class);
        }
        if(superviseEnclosureVoList!=null){
            for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                int lastIndexOf = superviseEnclosureVo.getEnclosureUrl().lastIndexOf(".");
                //获取文件的后缀名 .jpg
                String suffix = superviseEnclosureVo.getEnclosureUrl().substring(lastIndexOf);
                if(".pdf".equals(suffix)){
                    superviseEnclosureVos.add(superviseEnclosureVo);
                }
            }
            DocumentAdapter adapter=new DocumentAdapter(superviseEnclosureVos);
            rv_document.setAdapter(adapter);
        }
    }
    private void getSuperviseInspectionVo(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        DocumentService vs = retrofit.create(DocumentService.class);
        Map<String,String > params = new LinkedHashMap<String, String>();
        params.put("id", id);
        if("1".equals(type)){
            jsonForResultCall = vs.getSupervisionInspectioById(application.getAccessToken(), params);
        }else if("2".equals(type)){
            jsonForResultCall = vs.getDoubleRandomInspectionDetailById(application.getAccessToken(), params);
        }else if("3".equals(type)){
            jsonForResultCall = vs.getSupervisionInspectionSpecialDetailById(application.getAccessToken(), params);
        }
        if("4".equals(type)){
            supervisionInspectionVo = JSON.parseObject(getIntent().getStringExtra("supervisionInspectionVo"), SupervisionInspectionVo.class);
            setDate(supervisionInspectionVo);
        }else{
            jsonForResultCall.enqueue(new Callback<JsonForResult>() {
                @Override
                public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                    if(_dialog != null)_dialog.cancel();
                    try {
                        JsonForResult jsonForResult = (JsonForResult) response.body();
                        if (jsonForResult != null && jsonForResult.isSuccess()) {
                            if (jsonForResult.getData() != null) {
                                supervisionInspectionVo = JSON.parseObject(jsonForResult.getData().toString(), SupervisionInspectionVo.class);
                                setDate(supervisionInspectionVo);
                            } else {

                            }
                        } else {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    } catch (Exception e) {
                        if(_dialog != null)_dialog.cancel();
                    }
                }

                @Override
                public void onFailure(Call<JsonForResult> call, Throwable t) {
                    if(_dialog != null)_dialog.cancel();
                    String msg = "网络异常!";
                    if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg+t.getMessage();
                    UtilHelper.alertMsg(context, "错误", msg);
                }
            });
        }

    }
    public class DocumentAdapter extends RecyclerView.Adapter<DocumentAdapter.ViewHolder> {
        private List<SuperviseEnclosureVo> superviseEnclosureVoList;
        public DocumentAdapter(List<SuperviseEnclosureVo> superviseEnclosureVoList) {
            this.superviseEnclosureVoList = superviseEnclosureVoList;
        }
        @Override
        public DocumentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_document_2, parent, false);
            DocumentAdapter.ViewHolder viewHolder = new DocumentAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull DocumentAdapter.ViewHolder holder, int position) {
            holder.btn_title.setText(superviseEnclosureVoList.get(position).getEnclosureName());
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, DocumentReprinterActivity.class);
                    intent.putExtra("url", superviseEnclosureVoList.get(position).getEnclosureUrl());
                    intent.putExtra("name", superviseEnclosureVoList.get(position).getEnclosureName());
                    intent.putExtra("unitName", supervisionInspectionVo.getUnitName());
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return superviseEnclosureVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            Button btn_title;
            RelativeLayout relativeLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.btn_title = itemView.findViewById(R.id.btn_title);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }
}